<template>
    <div>
        <div class="search">
            <input v-model="keyword" class="search-input" type="text" placeholder="请输入城市名或拼音" />
        </div>
        <div class="search-content" ref="search" v-show="this.keyword">
            <ul >
                <li class="search-item border-bottom"
                    v-for="item in list"
                    :key="item.id"
                    @click="Handleclick(item.name)"
                >{{item.name}}</li>
                <li class="search-item border-bottom" v-show="!this.list.length">没有找到符合的结果</li>
            </ul>
        </div>
    </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: {
      type: Object
    }
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  watch: {
    keyword () {
      if (!this.keyword) {
        this.list = []
        return
      }
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted: function () {
    this.scroll = new Bscroll(this.$refs.search)
  },
  methods: {
    Handleclick: function (cityname) {
      this.$store.dispatch('changeCity', cityname)
      this.$router.push('/')
    }
  }
}
</script>

<style scoped lang="stylus">
    @import '~styles/variables.styl'
    .search
      height: 0.72rem
      padding: 0 0.3rem
      background-color: $bgcolor
      box-sizing: border-box
      .search-input
          height: 0.6rem
          width: 100%
          line-height: 0.6rem
          text-align: center
          border-radius: 0.05rem
          font-size: 0.26rem
          color: #666666
    .search-content
      overflow: hidden
      position: absolute
      left: 0
      top: 1.58rem
      right: 0
      bottom: 0
      background: #eeeeee
      z-index: 1
      .search-item
        line-height: 0.62rem
        padding-left: .3rem

</style>
